package zoo.member.admin.pro.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import zoo.member.admin.pro.dao.AdminProductDao;
import zoo.member.admin.pro.domain.AdminProductCommand;
import zoo.member.admin.util.FileUtil;

@Controller
@RequestMapping("/admin/write.do")
public class AdminProductWriteController {
	@Autowired
	private AdminProductDao apDao;
	
	@RequestMapping(method=RequestMethod.GET)
	public String form(){
		return "product_write";
	}
	
	@ModelAttribute("adminProduct")
	public AdminProductCommand formBacking(){
		return new AdminProductCommand();
	}
		
	@RequestMapping(method = RequestMethod.POST)
	public String submit(@ModelAttribute("adminProduct") AdminProductCommand product, /*BindingResult errors*/MultipartHttpServletRequest request) throws Exception{
		
		/*new FileValidator().validate(command, errors);*/
		
		/*if(errors.hasErrors()){
			return "file/fileUploadForm";
		}*/
		
		String path = "D:/javaWork/workspace-spring/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/urkr/adminproductupload";
		
		//다중 업로드 MultipartHttpServletRequest 사용해서 List로 반환
		//view에 <input type="file" name="reportFile"> 파라미터 네임을 단일하게 지정
		
		List<MultipartFile> list = request.getFiles("reportFile");
		String filename = "";
		if(list !=null && list.size()>0){
			for(int i=0;i<list.size();i++){
				MultipartFile m = list.get(i);
				if(m !=null && !m.isEmpty()){
					filename = FileUtil.rename(m.getOriginalFilename());
															
					File file = new File(path+ "/" + filename);
					
					try {
						m.transferTo(file);
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					if(i == 0) product.setP_listimage(filename);
					else if(i == 1) product.setP_previewimage1(filename);
					else if(i == 2) product.setP_previewimage2(filename);
					else if(i == 3) product.setP_previewimage3(filename);
					else if(i == 4) product.setP_productimage1(filename);
					else if(i == 5) product.setP_productimage2(filename);
					else if(i == 6) product.setP_productimage3(filename);
				}
			}
			apDao.insert(product);
		}
			
			return "redirect:/admin/prolist.do";

	}
}
